package com.zrb.mobile;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.zrb.mobile.adapter.Project_commentstatAdapter;
import com.zrb.mobile.adapter.model.CommentStatisticDto;
import com.zrb.mobile.adapter.model.OwnProjectDetailDto;
import com.zrb.mobile.adapter.model.OwnProjectDetailDtos;
import com.zrb.mobile.adapter.model.inspectStatisticDto;
import com.zrb.mobile.fadingactionbar.SherlockFadingActionBarHelper;
import com.zrb.mobile.ui.LinearLayoutForListView;
import com.zrb.mobile.ui.SimpleViewPagerIndicator;
import com.zrb.applib.utils.AppSetting;
 
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ZrbRestClient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class User_my_projectinfo extends SherlockFragmentActivity implements OnClickListener{

	
    private Bitmap mBmp = null;
  //  private Drawable mDrawable = null;
	private Fragment currentFragment = null;
	LinearLayout layout_container;
	LinearLayoutForListView attachlistview;
	//CustomloadingView mloadingView;
	int curPageindex=0;
	int projectId;
	TextView projectTitle,projectPeriod,projectInvestment;
	TextView projectRelpy;
	Project_commentstatAdapter mcommentCountAdapter;
 
	ImageView projectimg;
	//RelativeLayout mtitleLayout;
	ImageView mreportHeadlayout;
	//ObserveScrollView mscrollview;
	private String[] mTitles = new String[] { "关注", "分享", "勘察" };
	SimpleViewPagerIndicator mIndicator;
	ViewPager mViewPager;
	OwnProjectDetailDto myProjectDto;
	
	TextView minvestmentCount,mlookCount,minspectCount;
	  View customNav;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

	     SherlockFadingActionBarHelper helper = new SherlockFadingActionBarHelper()
	        .actionBarBackground(R.drawable.app_bg3)
	        .headerLayout(R.layout.u_center_myproject_head)
	        .contentLayout(R.layout.u_center_myproject_content);;
	        
	     setContentView(helper.createView(this));
	     helper.initActionBar(this); 
	  
	     getSupportActionBar().setDisplayShowTitleEnabled(false);
	     getSupportActionBar().setDisplayShowHomeEnabled(false);
	 
	        //Inflate the custom view
	     customNav = LayoutInflater.from(this).inflate(R.layout.project_fadingbar, null);
	    // getSupportActionBar().setCustomView(customNav,new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
	    // getSupportActionBar().setCustomView(customNav,new  ActionBar.LayoutParams());//ViewGroup.LayoutParams

		getSupportActionBar().setCustomView(
				customNav,
				new com.actionbarsherlock.app.ActionBar.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)

		);
	     getSupportActionBar().setDisplayShowCustomEnabled(true);
 	 
	//	setContentView(R.layout.u_center_myprojectinfo);
 
		if (bundle != null)
			restoreSelf(bundle);
		else {
			projectId = this.getIntent().getIntExtra("projectId",-1);
 		}
		 initView();
		   initViewpager();
 		// LoadData();
 	}
 	 
	@Override
	protected  void onSaveInstanceState(Bundle outState)  {
        super.onSaveInstanceState(outState);
        outState.putInt("projectId", projectId);
    }

    private void restoreSelf(Bundle savedInstanceState){
    	projectId = savedInstanceState.getInt("projectId",-1);
    }
	
    private void setFragment(Fragment fragment) {
        setFragment(fragment, null);
    }

    private void setFragment(Fragment fragment, String name) {
       if (fragment != currentFragment) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            if (name != null) ft.addToBackStack(name);
            ft.replace(R.id.content_frame, fragment).commit();
            currentFragment = fragment;
        }
    }
	
  //  TextView projectTitle,projectPeriod,projectInvestment;
	private void initView(){
 	
 		View lefticon= customNav.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
	 	TextView txtTitle=	(TextView)customNav.findViewById(R.id.txt_title);
		txtTitle.setText("项目报告"); 
	 	
	 	mreportHeadlayout=(ImageView)this.findViewById(R.id.project_report_headlayout);
 	 	projectimg=(ImageView)this.findViewById(R.id.myproject_newsImg);
		
		projectTitle=	(TextView)this.findViewById(R.id.txt_myproject_title);
		projectPeriod=	(TextView)this.findViewById(R.id.txt_myproject_period);
		projectInvestment=	(TextView)this.findViewById(R.id.txt_myproject_investment);
 		
		minvestmentCount=(TextView)this.findViewById(R.id.investment_count);
		mlookCount=(TextView)this.findViewById(R.id.look_count);
		minspectCount=(TextView)this.findViewById(R.id.inspect_count);
 
		projectRelpy=(TextView)this.findViewById(R.id.tv_replycount);
 		
		attachlistview=(LinearLayoutForListView)this.findViewById(R.id.attach_listview);
 		//mloadingView=(CustomloadingView)this.findViewById(R.id.list_emptyview);
		//mloadingView.SetOnRefleshListener(this);
		this.findViewById(R.id.tv_commentdetail).setOnClickListener(new OnClickListener(){
 			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				 Intent it4 = new Intent(User_my_projectinfo.this, Project_commentlist_Activity.class);
				 it4.putExtra("projectId", projectId);
			     startActivity(it4);
			}
 		} ); 
		
		mIndicator = (SimpleViewPagerIndicator) findViewById(R.id.report_chat_indicator);
		mIndicator.setTitles(mTitles);
		mViewPager = (ViewPager) findViewById(R.id.report_chat_viewpager);
		mViewPager.setOffscreenPageLimit(3);
  	}
	
	private void initViewpager() {
 		FragmentPagerAdapter mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
			@Override
			public int getCount() { return mTitles.length; }

			@Override
			public Fragment getItem(int position) {
 				return  getCurrentFragment(position+1);
			}
		};

		mViewPager.setAdapter(mAdapter);
		mViewPager.setCurrentItem(0);
		mViewPager.setOnPageChangeListener(new OnPageChangeListener()
		{
			@Override
			public void onPageSelected(int position){
				mIndicator.setSelectTextAt(position);
			}
  
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				
				CommonUtil.InfoLog("onPageScrolled", position+","+positionOffset);
				mIndicator.scroll(position, positionOffset);
			}

			@Override
			public void onPageScrollStateChanged(int state){}
		 
		});

	}
	private void LoadData()
	{
		//http://172.17.2.13:8090//projectApi/myProjectDetail?projectId=10294
		// projectId=10294;
		//mloadingView.HideText("努力加载中~~").ShowLoading();
     	String url=String.format("projectApi/myProjectDetail?projectId=%1$s",projectId);
     	url+="&zrb_front_ut="+AppSetting.curUser.zrb_front_ut;
     	
     	CommonUtil.InfoLog("myProjectDetail", url);
      
  		ZrbRestClient.get(url, null,  new AsyncHttpResponseHandler()
    	{
		 
 			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
 				//mloadingView.HideText("加载数据出错！").ShowRefleshBtn(true).ShowError();
			}
 		   @Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
  				String results=new String(arg2);
				try 
				{
 					 Gson gson = new Gson();  
					  OwnProjectDetailDtos tmpDto=	gson.fromJson(results, OwnProjectDetailDtos.class);
 	 			       if(tmpDto.res==1) {
	 			    	  // mloadingView.Hide();
	 			    	   mcommentCountAdapter=new Project_commentstatAdapter(User_my_projectinfo.this);
	 			    	   projectTitle.setText(tmpDto.data.projectName);
	 			    	   projectPeriod.setText("招商时长："+tmpDto.data.period);
	 			    	   projectInvestment.setText("项目总额："+tmpDto.data.investment);
	 			    	   
	 			    	  // projectlooknum.setText("成功看地人数："+tmpDto.data.inspectNum+"人");
	 			    	   projectRelpy.setText("回复统计："+tmpDto.data.commentNum+"条");
	 			    	   minvestmentCount.setText(String.valueOf(tmpDto.data.inviteNum));
	 			    	   mlookCount.setText(String.valueOf(tmpDto.data.viewNum));
	 			    	   minspectCount.setText(String.valueOf(tmpDto.data.inspectNum));
	 			    	   //displayImage(String uri, ImageView imageView, ImageLoadingListener listener)
	 			    	   if(!TextUtils.isEmpty(tmpDto.data.pic)) 
	 			    		   new DownloadTask().execute(AppSetting.mediaServer+tmpDto.data.pic);
	 			    		  // imageLoader.displayImage(AppSetting.mediaServer+tmpDto.data.pic, projectimg,tmploadlistener);
	 			    	   
	 			    	   showComment(tmpDto.data.commentStatistics);
	 			    	   myProjectDto=tmpDto.data;
	 			    	   initViewpager();
	 			    	  // showinspectChat(tmpDto.data.inspectStatistics);
 	 			      }
	 			      else {}
	 			    	// mloadingView.HideText("错误："+tmpDto.msg).ShowRefleshBtn(true).ShowError();
 			      
     			}
				catch(Exception e){
					//mloadingView.HideText(e.getMessage()).ShowRefleshBtn(true).ShowError();
 				}
  			}});
 	}
  
 	 /**
     * Asynchronous image download task
     */
    class DownloadTask extends AsyncTask<String, Void, String>{
        
        private String mTaskUrl;
   
        @Override
        public String doInBackground(String... params) {

            mTaskUrl = params[0];
            InputStream stream = null;
            URL imageUrl;
            Bitmap bmp = null;
          
            try {
                imageUrl = new URL(mTaskUrl);
                try {
                    stream = imageUrl.openStream();
                    bmp = BitmapFactory.decodeStream(stream);
                
                    try {
                        if(bmp != null){
                                mBmp = bmp;
                         }
                    } catch (NullPointerException e) {
                        Log.w("User_my_projectinfo", "Failed to cache "+mTaskUrl);
                    } 
                } catch (IOException e) {
                    Log.w("User_my_projectinfo", "Couldn't load bitmap from url: " + mTaskUrl);
                } finally {
                    closeStream(stream);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            return mTaskUrl;
        }
        
        private void closeStream(InputStream is){
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
   
        @Override
        public void onPostExecute(String url) {
            super.onPostExecute(url);
              if(mBmp != null){
              	   User_my_projectinfo.this.projectimg.setImageBitmap(mBmp); 
               	   User_my_projectinfo.this.mreportHeadlayout.setImageBitmap(mBmp);
               	   FadeInBitmapDisplayer.animate(User_my_projectinfo.this.mreportHeadlayout, 500);
             }  
        }

    };
 	
	
	private void showinspectChat(List<inspectStatisticDto> inspectStatistics){
		
		 if(inspectStatistics!=null&&inspectStatistics.size()>0){
		    setFragment(MarkedPointsChartFragment.newInstance("MarkedPoint",inspectStatistics,1) );
		 }
	}
	
	private Fragment getCurrentFragment(int postion){
		
	 List<inspectStatisticDto> inspectStatistics=new ArrayList<inspectStatisticDto>();
	 /*		 if(postion==1){
			 inspectStatistics=myProjectDto.collectionStatistics;
 		 }
		 else if(postion==2){
 			 inspectStatistics=myProjectDto.shareStatistic;
 		 }
		 else
			 inspectStatistics=myProjectDto.inspectStatistics; */
 	   for(int i=0;i<7;i++){
 		 inspectStatisticDto tmp =new inspectStatisticDto();
			 tmp.date="2015-02-03";
			 tmp.number=(int) (Math.random() * (100 - 1) + 1);
			 inspectStatistics.add(tmp);
		 }  
		 
		return MarkedPointsChartFragment.newInstance("MarkedPoint",inspectStatistics,postion);
	}
	
	private String[] commentType={"资金积压","结算方式","项目地段","规划条件","价格贵","政府偿还能力","其它"};
	
	private void showComment(List<CommentStatisticDto> commentStatistics){
		   mcommentCountAdapter=new Project_commentstatAdapter(User_my_projectinfo.this);
		   if(commentStatistics!=null&&commentStatistics.size()>0){
			   mcommentCountAdapter.CurrentDatas.addAll(commentStatistics);
	           attachlistview.setAdapter(mcommentCountAdapter);
	       }
		   else{
			   commentStatistics=new ArrayList<CommentStatisticDto>();
			   for(int i=0;i<commentType.length;i++){
				   CommentStatisticDto tmpdto=new CommentStatisticDto(commentType[i], "0.0%");//(i%2==0) ?"23.4%":
				   commentStatistics.add(tmpdto);
			   }
			   mcommentCountAdapter.CurrentDatas.addAll(commentStatistics);
	           attachlistview.setAdapter(mcommentCountAdapter);   
 		   }
 	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
    
     	case R.id.right_title:
     		//changeBaseInfo() ;
     		break;
    	case R.id.btn_reflesh:
    		LoadData();
      		break;
     	 
 		}
 	}
 
  
}
